//
//  ViewController.m
//  XMAudioView
//
//  Created by lishi on 2019/2/20.
//  Copyright © 2019 lishi. All rights reserved.
//

#import "ViewController.h"

#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

#define kSCREEN_WIDTH [UIScreen mainScreen].bounds.size.width

#define kSCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height


@interface ViewController ()
<
    AVAudioRecorderDelegate,
    AVAudioPlayerDelegate
>

@property (nonatomic, strong) UIButton *playButton; // 播放按钮

@property (nonatomic, strong) UIButton *recordButton; // 录音按钮

@property (nonatomic, strong) AVAudioRecorder *recorder;

@property (nonatomic, copy) NSString *filePath;

@property (nonatomic, strong) NSURL *recordFileUrl;

@property (nonatomic, strong) AVAudioSession *session;

@property (nonatomic, strong) AVAudioPlayer *player;



@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.playButton];
    [self.view addSubview:self.recordButton];
    
    [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
        if (granted) {
            NSLog(@"麦克风打开了");
        } else {
            NSLog(@"麦克风关闭了");
        }
    }];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationItem.title = @"音频处理第一版";
}


/**
 * 点击播放按钮
 */
- (void)playClick:(UIButton *)sender {
//    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:self.recordFileUrl error:nil];
//    [self.session setCategory:AVAudioSessionCategoryPlayback error:nil];
//    BOOL success = [self.player play];
//    if (success) {
//        NSLog(@"播放成功");
//    }else{
//        NSLog(@"播放失败");
//    }
    
    [self.session setCategory:AVAudioSessionCategoryPlayback error:nil];
    SystemSoundID soundID;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(self.recordFileUrl), &soundID);
    AudioServicesPlaySystemSound(soundID);
}

- (void)playCallback {
    NSLog(@"播放成功");
}

/**
 * 点击录音按钮
 */
- (void)recordClick:(UIButton *)sender {
    // 1. 获取麦克风权限
    if (![self canRecord]) {
        NSLog(@"请启用麦克风-设置/隐私/麦克风");
        [self userOpenRecord];
        return ;
    }
    sender.selected = !sender.selected;
    
    if (sender.isSelected == YES) {
        // 开启录制方法
        
        AVAudioSession *session =[AVAudioSession sharedInstance];
        NSError *sessionError;
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        if (session == nil) {
            NSLog(@"Error creating session: %@",[sessionError description]);
        }else{
            [session setActive:YES error:nil];
        }
        self.session = session;
        
        //1.获取沙盒地址
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
//        _filePath = [path stringByAppendingString:@"/record.wav"];
//        _filePath = [path stringByAppendingString:@"/record.caf"];
        _filePath = [path stringByAppendingString:@"/record.acc"];
//        _filePath = [path stringByAppendingString:@"/record.mp3"];
        
        //2.获取文件路径
        self.recordFileUrl = [NSURL fileURLWithPath:_filePath];
        
        //设置参数
//        NSDictionary *recordSetting = [[NSDictionary alloc] initWithObjectsAndKeys:
//                                       //采样率  8000/11025/22050/44100/96000（影响音频的质量）
//                                       [NSNumber numberWithFloat: 8000.0],AVSampleRateKey,
//                                       // 音频格式
//                                       [NSNumber numberWithInt: kAudioFormatLinearPCM],AVFormatIDKey,
//                                       //采样位数  8、16、24、32 默认为16
//                                       [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
//                                       // 音频通道数 1 或 2
//                                       [NSNumber numberWithInt: 1], AVNumberOfChannelsKey,
//                                       //录音质量
//                                       [NSNumber numberWithInt:AVAudioQualityHigh],AVEncoderAudioQualityKey,
//                                       nil];
        
        NSDictionary *recordSetting = @{AVFormatIDKey:@(kAudioFormatMPEG4AAC),
                                        AVEncoderAudioQualityKey:@(AVAudioQualityMax),
                                        AVSampleRateKey: @11025.0f,
                                        AVNumberOfChannelsKey: @2,
                                        AVLinearPCMBitDepthKey: @16};
        
//        NSDictionary *recordSetting = @{AVFormatIDKey:@(kAudioFormatMPEGLayer3),
//                                        AVEncoderAudioQualityKey:@(AVAudioQualityMax),
//                                        AVSampleRateKey: @11025.0f,
//                                        AVNumberOfChannelsKey: @2,
//                                        AVLinearPCMBitDepthKey: @16};
        
        _recorder = [[AVAudioRecorder alloc] initWithURL:self.recordFileUrl settings:recordSetting error:nil];
        _recorder.delegate = self;
        if (_recorder) {
            _recorder.meteringEnabled = YES;
            [_recorder prepareToRecord];
            [_recorder record];
            NSLog(@"开始录音");
        } else {
            NSLog(@"音频格式和文件存储格式不匹配,无法初始化Recorder");
        }
        
//        AudioComponentDescription outputUinitDesc;
//        memset(&outputUinitDesc, 0, sizeof(AudioComponentDescription));
//        outputUinitDesc.componentType = kAudioUnitType_Output;
//        outputUinitDesc.componentSubType = kAudioUnitSubType_RemoteIO;
//        outputUinitDesc.componentManufacturer = kAudioUnitManufacturer_Apple;
//        outputUinitDesc.componentFlags = 0;
//        outputUinitDesc.componentFlagsMask = 0;
//        AudioComponent outComponent = AudioComponentFindNext(NULL, &outputUinitDesc);
//
//        OSStatus status = AudioComponentInstanceNew(outComponent, &_outAudioUinit);
//        AudioStreamBasicDescription recordFormat;
//        recordFormat.mSampleRate = 44100;
//        recordFormat.mFormatID = kAudioFormatLinearPCM;
//        recordFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger;
//        recordFormat.mFramesPerPacket = 1;
//        recordFormat.mChannelsPerFrame = 1;
//        recordFormat.mBitsPerChannel = 16;
//        recordFormat.mBytesPerFrame = recordFormat.mBytesPerPacket = 2;
//        status = AudioUnitSetProperty(recordUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &recordFormat, sizeof(recordFormat));
        
    } else {
        // 停止录音
        NSLog(@"停止录音");
        [_recorder stop];

        NSFileManager *manager = [NSFileManager defaultManager];
        if ([manager fileExistsAtPath:_filePath]){

            NSString *size = [NSString stringWithFormat:@"%.2lluKb",[[manager attributesOfItemAtPath:_filePath error:nil] fileSize] / 1024];

            NSLog(@"size === %@",size);
        }
        
    }
}

/**
 * 开启麦克风权限
 */
- (void)userOpenRecord {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请您开启麦克风权限" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication]canOpenURL:url]) {
            [[UIApplication sharedApplication]openURL:url];
        }
    }]];
    
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

/**
 * 检查是否拥有麦克风权限
 */
- (BOOL)canRecord {
    __block BOOL bCanRecord = YES;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
        [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
            if (granted) {
                bCanRecord = YES;
            } else {
                bCanRecord = NO;
            }
        }];
    }
    return bCanRecord;
}

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
    NSLog(@"录音完成");
}

- (void)audioRecorderEncodeErrorDidOccur:(AVAudioRecorder *)recorder error:(NSError * __nullable)error {
 
}

- (UIButton *)recordButton {
    if (!_recordButton) {
        _recordButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _recordButton.frame = CGRectMake(15, (kSCREEN_HEIGHT - 35) / 2, 100, 35);
        _recordButton.backgroundColor = [UIColor blueColor];
        [_recordButton setTitle:@"录音" forState:UIControlStateNormal];
        _recordButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_recordButton addTarget:self action:@selector(recordClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _recordButton;
}

- (UIButton *)playButton {
    if (!_playButton) {
        _playButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _playButton.frame = CGRectMake(kSCREEN_WIDTH - 115, (kSCREEN_HEIGHT - 35) / 2, 100, 35);
        _playButton.backgroundColor = [UIColor greenColor];
        [_playButton setTitle:@"播放" forState:UIControlStateNormal];
        _playButton.titleLabel.font = [UIFont systemFontOfSize:16];
        [_playButton addTarget:self action:@selector(playClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _playButton;
}


@end
